import re
import asyncio
from datetime import datetime

get_loop = asyncio.get_running_loop if hasattr(asyncio, "get_running_loop") else \
    asyncio.get_event_loop

async def resolve(addr):
    try:
        info = await get_loop().getaddrinfo(addr, None)
        addr = info[0][4][0]
    except:
        addr = None

    return addr


def isdomain(text, alphabet=set('abcdefghijklmnopqrstuvwxyz')):
    return not alphabet.isdisjoint(text.lower())


async def check(proxy):

    url = proxy["url"]

    host = re.search(r'server=(.+)&port', url).group(1)
    port = re.search(r'port=(.+)&secret', url).group(1)

    host = await resolve(host) # Get ip


    if host:
        ping_pong = datetime.now()

        try:
            _, writer = await asyncio.wait_for(asyncio.open_connection(host, port), 5)

            #proxy["ping"] = datetime.now() - ping_pong
            proxy["ping"] = round((datetime.now() - ping_pong).total_seconds() * 1000, 3)

            writer.close()
            await writer.wait_closed()

            proxy["up"] = True

        except:
            pass

    return proxy


async def sort_by_ping(results, tg):
    proxy_up = filter(lambda proxy: proxy["up"], results)
    for proxy in sorted(proxy_up, key=lambda x: x["ping"]):
        if tg:
            print("Proxy: {}  Ping: {}ms".format(proxy["url"].replace("https://t.me","tg:/"), proxy["ping"]))
        else:
            print("Proxy: {}  Ping: {}ms".format(proxy["url"], proxy["ping"]))